package com.buka.config;

import lombok.Data;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
@Data
public class MQConfig {

    /**
     * 交换机
     */
    @Value("${mqconfig.coupon_exchange}")
    private String couponExchange;


    /**
     * 第一个队列  延迟队列，
     */
    @Value("${mqconfig.coupon_release_delay_queue}")
    private String couponReleaseDelayQueue;

    /**
     * 第一个队列的路由key
     * 进入队列的路由key
     */
    @Value("${mqconfig.coupon_release_delay_routing_key}")
    private String couponReleaseDelayRoutingKey;


    /**
     * 第二个队列，被监听恢复库存的队列
     */
    @Value("${mqconfig.coupon_release_queue}")
    private String couponReleaseQueue;

    /**
     * 第二个队列的路由key
     * <p>
     * 即进入死信队列的路由key
     */
    @Value("${mqconfig.coupon_release_routing_key}")
    private String couponReleaseRoutingKey;

    /**
     * 过期时间
     */
    @Value("${mqconfig.ttl}")
    private Integer ttl;


    //创建队列，创建交换机

    @Bean
    public Exchange couponExchange() {
        return new TopicExchange(couponExchange, true, false);
    }

    @Bean
    public Queue releaseQueue() {
        return new Queue(couponReleaseQueue, true, false, false);
    }

    @Bean
    public Queue delayQueue() {
        //配置延时队列的参数，延时时间，超时后转发的交换机，路由key
        Map<String, Object> args = new HashMap<>();
//        超时时间
        args.put("x-message-ttl", ttl);
//        超时转发的路由
        args.put("x-dead-letter-routing-key", couponReleaseRoutingKey);
//        超时转发的交换机
        args.put("x-dead-letter-exchange", couponExchange);

        return new Queue(couponReleaseDelayQueue, true, false, false,args);
    }

    //创建延时队列绑定关系
    @Bean
    public Binding delayQueueBinding() {
        return new Binding(couponReleaseDelayQueue,Binding.DestinationType.QUEUE,
                            couponExchange,couponReleaseDelayRoutingKey,null);
    }


    //创建死信队列绑定关系
    @Bean
    public Binding releaseBinding() {
        return new Binding(couponReleaseQueue,Binding.DestinationType.QUEUE,
                couponExchange,couponReleaseRoutingKey,null);
    }

    //消息转化器
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

}
